#include <cstdio>
#include <iostream>
#include <vector>
#include <tr1/memory>

#include <boost/foreach.hpp>

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

#include "output.h"
#include "page_db.h"
#include "flat_output.h"
#include "junix.h"
#include "idxutils.h"

namespace jsearch
{

flat_output::flat_output( std::tr1::shared_ptr<page_db>& db,
		                  std::tr1::shared_ptr<std::vector<std::string> >& qs,
	                      bool vbs)
:verbose_mode(vbs)
{
	pdb=db;
	querys=qs;
}

// flat text out put format
void flat_output::put( std::vector<prio_page>& ppv)
{
	setbuf(stdout,NULL);
	printf("{ %u documents }\n\n", ppv.size());

	const int buf_size=4096;
	char buf[buf_size];
	char nbuf[buf_size];

	std::vector<prio_page>::iterator pos=ppv.begin();
	for( ;pos!=ppv.end();pos++) {
		std::string path=pdb->getnamebyid( pos->page_id );
		if (path.empty())
			continue;

		struct stat sb;
		if (!stat(path.c_str(), &sb)) {
			printf("[%s]\n",path.c_str());
			if (verbose_mode) {
				int line=1;
				int match_line=1;
				FILE *fp=fopen(path.c_str(),"r");
				if (!fp)
					err_ret("error:file %s open error", path.c_str());

				std::vector<std::string>::iterator pos;

				while (fgets(buf,buf_size,fp) != NULL) {
					std::string  ls;
					BOOST_FOREACH(std::string& s, *querys) {
						strncpy(nbuf,buf,buf_size);
						ls = str_tolower(s);

						if (strstr(str_tolower(nbuf), ls.c_str()) != NULL) {
							match_line ++;
							printf("  %03d: %s",line,buf);
							break;
						}
					}	   

					line ++;

					if (match_line>8)
						break;
				}

				clearerr(fp);
				fclose(fp);
				printf("\n\n");
			}
		}
	}
}

}//end namespace
